<template>
    <div>
      <la-dialog
        ref="dialogRef"
        :title="dialogTitle"
        :async="true"
        width="550px"
        @confirm="handleSubmit"
        @cancel="handleClose"
      >
        <el-form
          ref="formRef"
          :model="formData"
         
          label-width="84px"
          :rules="formRules"
        >
   
          <el-form-item label="权限">
            <el-tree
            default-expand-all
            :data="menuTree"
            node-key="permission_mark"
    :props="{label:'permission_name'}"
    :default-checked-keys="formData.defaultCheckedKeys"
            ref="prmissionRef"
    show-checkbox
    @check-change="handleCheckChange"
  />
          </el-form-item>
         
        </el-form>
      </la-dialog>
    </div>
  </template>
  <script setup>
  import api from "@/app/admin/api";
  import laDialog from "@/lite/components/la-dialog/index.vue";
  import { reactive, ref, computed, nextTick } from "vue";
  import feedback from "@/lite/utils/feedback";
  
  const emit = defineEmits(["success", "close"]);
  const dialogRef = ref(null);
  const formRef = ref(null);
  const mode = ref("add");
  const menuTree = ref([]);
  const prmissionRef = ref()
  const formData = ref({
    id:0,
    defaultCheckedKeys:[]
  });
  const formRules = reactive({
    username: [
      { required: true, message: "请输入用户名", trigger: "blur" },
      { min: 3, message: "用户名最小为3个字符串" },
    ],
  });
  
  const roleOptions = ref([]);
  
  const dialogTitle = computed(() => {
    return mode.value == "edit" ? "编辑用户" : "新增用户";
  });
  
  const getRoleOptions = async () => {
    const roleRes = await api.role.list();
    roleOptions.value = roleRes.data;
    
  };
  
  const setFormData = async (row) => {
    const res = await api.menu.list({});
    menuTree.value = res.data;
    formData.value.id = row.id;
    formData.value.defaultCheckedKeys = row.rules
   
  };
  
  const open = (type = "add") => {
    mode.value = type;
    dialogRef.value.open();
  };
  const close = () => {
    formRef.value.resetFields();
    dialogRef.value.close();
    emit("close");
  };
  const handleSubmit = async () => {
    await formRef.value?.validate();
    const getCheckedKeys = prmissionRef.value.getCheckedKeys()
    const id = formData.value.id;
    let res = await api.role.update({rules:getCheckedKeys,id});
    // if (mode.value == "add") {
    //   res = await api.admin.create(formData.value);
    // } else {
    //   res = await api.admin.update(formData.value);
    // }
  
    if (!res.error) {
      close();
      emit("success");
      feedback.msgSuccess(res.msg);
    } else {
      feedback.msgError(res.msg);
    }
  };
  const handleClose = async () => {
    close();
  };
  getRoleOptions();
  defineExpose({
    open,
    setFormData,
  });
  </script>
  